import { Injectable } from '@angular/core';
import { AppStoreModule } from './store.module';
import { Store, select } from '@ngrx/store';
import { getPlayer } from './selector/play.selector';
import { PlayState } from './entity';
import { setSongList, setPlayList, setCurrentIndex } from './actions/play.actions';
import { shuffleList } from '../util/array.util';
import { Song } from '../routes/entity';

@Injectable()
export class StoreActionService {

  private playState: PlayState;

  constructor(
    private store$: Store<AppStoreModule>
  ) {
    this.store$.pipe(select(getPlayer))
      .subscribe(res => this.playState = res);
  }

  /** 更新播放列表 */
  updatePlayList({ list, index }: { list: Song[], index: number }): void {
    this.store$.dispatch(setSongList({ songList: list }));
    let indexTemp = index;
    let listTemp = list.slice();
    if (this.playState.playMode.type === 'random') {
      listTemp = shuffleList(list || []);
      indexTemp = listTemp.findIndex(e => e.id === list[index].id);
    }
    this.store$.dispatch(setPlayList({ playList: listTemp }));
    this.store$.dispatch(setCurrentIndex({ currentIndex: indexTemp }));
  }

  /** 添加歌曲到播放列表 */
  insertSong(song: Song, isPlay: boolean): void {
    const playList = this.playState.playList.slice();
    const songList = this.playState.songList.slice();
    // 歌曲插入位置，默认位置是当前歌曲播放位置
    let insertIndex = this.playState.currentIndex;
    // 歌曲是否存在于播放列表中
    if (this.existedInPlayList(playList, song)) {
      if (isPlay) {
        insertIndex = playList.findIndex(e => e.id === song.id);
      }
    } else {
      songList.push(song);
      playList.push(song);
      if (isPlay) {
        insertIndex = playList.length - 1;
      }
      this.store$.dispatch(setPlayList({ playList }));
      this.store$.dispatch(setSongList({ songList }));
    }
    // 改变当前播放歌曲
    if (insertIndex !== this.playState.currentIndex) {
      this.store$.dispatch(setCurrentIndex({ currentIndex: insertIndex }));
    }
  }

  insertSongs(songs: Song[] = []): void {
    const playList = this.playState.playList.slice();
    const songList = this.playState.songList.slice();
    songs.forEach(song => {
      if (this.existedInPlayList(playList, song)) {
        return;
      }
      playList.push(song);
      songList.push(song);
    });

    this.store$.dispatch(setPlayList({ playList }));
    this.store$.dispatch(setSongList({ songList }));
  }

  private existedInPlayList(playList: Song[], song: Song): boolean {
    const index = playList.findIndex(e => e.id === song.id);
    return index > -1;
  }

}
